package com.reportingapplication.student;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.reportingapplication.student.R;
import com.reportingapplication.student.tools.ID;
import com.reportingapplication.student.tools.JSONParser;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Activity which asks student to write his name
 * @author Keith Davelaar
 */
public class SignupActivity extends Activity {
	/** Progress bar **/
	private ProgressDialog pDialog;
	
	/**
	 * Called when the Activity is created.
	 * Standard.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_signup);
	}

	/**
	 * Standard.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.signup, menu);
		return true;
	}
	
	@Override
	public void onBackPressed(){
		Intent i = new Intent(Intent.ACTION_MAIN);
		i.addCategory(Intent.CATEGORY_HOME);
		startActivity(i);
	}
    
    /** 
	 * Called when the user clicks the OK button.
	 * Handle the press.
	 */
	public void nextMenu(View view) {
		// Get the name from the textfield.
		EditText nameField = (EditText) findViewById(R.id.nameField);
		EditText pwdField = (EditText) findViewById(R.id.passwordField);
		// Something has to be filled in, otherwise do nothing.
		if(nameField.getText() != null && pwdField.getText() != null){
			String name = nameField.getText().toString();
			String password = pwdField.getText().toString();
			if(name.equals("") || password.equals("")){
				Toast toast = Toast.makeText(getApplicationContext(), "Vul a.u.b. beide velden in", Toast.LENGTH_LONG);
				toast.show();
			}else{
				(new SaveStudent()).execute(name, password);
			}
		}
	}
    
	/**
     * Class which saves the name of a new student
     */
    private class SaveStudent extends AsyncTask<String, String, String> {
        private boolean registered;
        int success;
        
		/**
         * Before starting background thread Show Progress Dialog
         */
    	@Override
		protected void onPreExecute() {
    		super.onPreExecute();
    		registered = false;
    		success = -1;
    		pDialog = new ProgressDialog(SignupActivity.this);
            pDialog.setMessage("Bezig te registreren. Een moment geduld...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {
			try {
				boolean successful = false;
				int counter = 0;
				while(!successful){
					// Get the name of the student and save this, together with the newly generated google_id
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					String name = args[0];
					String password = args[1];
					params.add(new BasicNameValuePair(ID.STUDENT_NAME, name));
					params.add(new BasicNameValuePair(ID.PASSWORD, password));
			        // Getting JSON string from URL
			        JSONParser jParser = new JSONParser();
			        JSONObject json = jParser.makeHttpRequest(ID.URL_ADD_STUDENT, ID.POST_REQUEST, params);
			        // Check that the request was successful
			        success = json.getInt(ID.TAG_SUCCESS);
			        if (success == 1) {
			        	// If successful log in student and save his/her google_id
			        	Editor edit = getSharedPreferences(ID.PREFS_NAME, 0).edit();
						edit.putBoolean(ID.LOGGED_IN, true);
						edit.putString(ID.STUDENT_NAME, json.getString(ID.STUDENT_NAME));
						edit.commit();
						successful = true;
						registered = true;
						// closing this screen
						finish();
			        }else if(success == 2){
			        	Toast toast = Toast.makeText(getApplicationContext(), "Vul a.u.b. correcte gegevens in", Toast.LENGTH_LONG);
						toast.show();
			        	successful = true;
			        }else{
			        	counter++;
			        	if(counter == 10){
			        		successful = true;
			        	}
			        }
				}
			} catch (JSONException e) {
				registered = false;
				Log.e(ID.ERROR, e.toString());
			} catch( Exception e){
				registered = false;
				Log.e(ID.ERROR, "Error: "+e.getClass().getName());
			}
			return null;			
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 **/
		@Override
		protected void onPostExecute(String file_url) {
			// Dismiss the dialog once done
			pDialog.dismiss();
			if(!registered && success == -1){
				Context context = getApplicationContext();
				CharSequence text = "Registreren niet gelukt door verbindingsprobleem, probeer a.u.b. later opnieuw";
				int duration = Toast.LENGTH_LONG;
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
			}else if(!registered && success == 2){
				Context context = getApplicationContext();
				CharSequence text = "Inloggegevens niet correct, probeer opnieuw";
				int duration = Toast.LENGTH_LONG;
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
			}else{
				// Return to the previous activity
				SignupActivity.this.finish();
			}
		}
	}
}
